package net.hxz.modules.controller;

import java.beans.PropertyEditorSupport;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.wy.commons.util.DeviceUtil;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;


/**
 * @author lcs
 *
 */
@Controller
public class BaseController {
	protected static final String ERROR_PATH = "error";
	protected static final String MAIN_PATH = "frontEnd/main";
	protected static final String PHONE_MAIN_PATH = "frontEnd/phone/main";
	protected static final String REDIRECT = "redirect:";
	
	@Autowired(required=false)
	protected HttpServletRequest request;
	@Autowired(required=false)
	protected HttpSession session;
	
	@InitBinder
	public void InitBinder(WebDataBinder dataBinder) {
		dataBinder.registerCustomEditor(Date.class,
				new PropertyEditorSupport() {
					public void setAsText(String value) {
						String formats[] = {"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd"};
						for( String format : formats ){
							try {
								setValue(new SimpleDateFormat(format).parse(value));
								return;
							} catch (Exception e) {}
						}
						setValue(null);
					}

					public String getAsText() {
						return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
								.format((Date) getValue());
					}

				});
		
		dataBinder.registerCustomEditor(Long.class,
                new PropertyEditorSupport() {
                    public void setAsText(String value) {
                        try {
                            setValue(Long.parseLong(value));
                        } catch (Exception e) {
                            setValue(-1L);
                        }
                    }

                    public String getAsText() {
                        return (String) getValue();
                    }
                });
        
        dataBinder.registerCustomEditor(long.class,
                new PropertyEditorSupport() {
                    public void setAsText(String value) {
                        try {
                            setValue(Long.parseLong(value));
                        } catch (Exception e) {
                            setValue(0L);
                        }
                    }

                    public String getAsText() {
                        return (String) getValue();
                    }
                });

        dataBinder.registerCustomEditor(Integer.class,
                new PropertyEditorSupport() {
                    public void setAsText(String value) {
                        try {
                            setValue(new Double(value).intValue());
                        } catch (Exception e) {
                            setValue(null);
                        }
                    }

                    public String getAsText() {
                        return (String) getValue();
                    }
                });
        
        dataBinder.registerCustomEditor(int.class,
                new PropertyEditorSupport() {
                    public void setAsText(String value) {
                        try {
                            setValue(new Double(value).intValue());
                        } catch (Exception e) {
                            setValue(0);
                        }
                    }

                    public String getAsText() {
                        return (String) getValue();
                    }
                });
		
		dataBinder.registerCustomEditor(Boolean.class,
				new PropertyEditorSupport() {
			public void setAsText(String value) {
				try {
					setValue(new Boolean(value).booleanValue());
				} catch (Exception e) {
					setValue(null);
				}
			}
			
			public String getAsText() {
				return (String) getValue();
			}
		});
		
		dataBinder.registerCustomEditor(String.class,
	        	new PropertyEditorSupport() {
		        	public void setAsText(String value) {
		        		if( value == null ){
		        			return;
		        		}
		        		
		        		//value = HTMLFilter.filterSensitive(value);
		        		setValue(value.replaceAll("\\r\\n", "<br />"));//保证textarea回车换行保留
		        	}
		        	
		        	public String getAsText() {
		        		return (String) getValue();
		        	}
	        });
	}
	
	/**
	 * 统一错误出口
	 * @param messages
	 * @return
	 */
	public Map<String , Object> createJSONError(ModelMap map, String... messages ){
		map.put("hasError" , true);
		for( int i = 0 , len = messages.length ; i < len ; i++){
			map.put("error_"+i, messages[i]);
		}
		return map;
	}

	/**
	 * 获取http host
	 * @return
	 */
	public String getHost() {
		return request.getScheme() + "://" + request.getServerName() + ( request.getServerPort() == 80 ? "" :  ":" + request.getServerPort()) + request.getContextPath();
	}
	
	public String getReferer(){
		String url = (String)session.getAttribute("referer");
		url = StringUtils.isBlank(url) ? "/" : url;
		url = Pattern.matches(".*(login|userLogin|supplierLogin).*", url) ? "/" : url;
		return url;
	}
	
	/**
	 * 判断访问源设备是手机还是pc
	 * @return true-手机，false-电脑或者识别不到
	 */
	public boolean isMobile(){
		return DeviceUtil.isMobile(request);
	}
	
	/**
	 * 判断访问源设备是手机还是pc
	 * 1、一般这个方法是在开发过程中测试调用的
	 * @param isMobile 是否通过代码检测，true-人工检测是手机返回，false-让代码自动检测返回
	 * @return true-手机，false-电脑或者识别不到
	 */
	public boolean isMobile(boolean isMobile){
		if(isMobile) return true;
		return DeviceUtil.isMobile(request);
	}
	
	/**
	 * 获取不同设备源的main路径
	 * @return main路径
	 */
	public String getMainPath(){
		return this.getMainPath(this.isMobile());
	}
	
	/**
	 * 获取不同设备源的main路径
	 * 1、一般这个方法是在开发过程中测试调用的
	 * @param isMobile 是否通过代码检测，true-人工检测是手机返回，false-让代码自动检测返回
	 * @return main路径
	 */
	public String getMainPath(boolean isMobile){
		if(this.isMobile(isMobile)){
			return PHONE_MAIN_PATH;
		}
		return MAIN_PATH;
	}
	
	/**
	 * 获取地址栏的地址
	 */
	public String getHref(HttpServletRequest request){
		StringBuffer ret = request.getRequestURL();
		
		String param = request.getQueryString();
		if(null != param){
			ret.append("?").append(param);
		}
		
		return ret.toString();
	}
}

